//
//  OTDR_SecondPageViewController.m
//  OTDR
//
//  Created by Liu on 2024/5/19.
//

#import "OTDR_SecondPageViewController.h"
#import "OTDR_ConfigInfoViewController.h"
#import "OTDR_LF_DrawViewController.h"

#import "OTDR_ConfigInfoModel.h"

@interface OTDR_SecondPageViewController ()<SocketSourceDataDelegate>
@property(nonatomic ,copy)NSString *modelConfig;
@property(nonatomic ,copy)NSString *waveConfig;
@property(nonatomic ,copy)NSString *avgTimeConfig;
@property(nonatomic ,copy)NSString *iorConfig;
@property(nonatomic ,copy)NSString *resolutionRatioConfig;

@property(nonatomic ,copy)NSString *rangeConfig;
@property(nonatomic ,copy)NSString *pulseConfig;
@property(nonatomic ,copy)NSString *attConfig;
/**
 *存放测试完成后返回的数据
 */
@property(nonatomic ,strong)NSMutableData *testBackData;
@property(nonatomic ,assign)NSInteger totalDataCount;
/**
 *当前是否在发送测试指令
 */
@property(nonatomic ,assign)BOOL isTest;
/**
 *<#define#>
 */
@property(nonatomic ,copy)NSString *fileNameStr;
@end



@implementation OTDR_SecondPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitleStr:@""];
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatUI];
    
    [self setDefaultCommand];
    
    self.socketServer.delegate = self;
    
    NSLog(@"int:%lu  uint32_t:%lu",sizeof(int),sizeof(uint32_t));
}

- (void )setDefaultCommand{
    NSArray *_configArr = [OTDR_ConfigInfoModel getConfigInfo];
    
    for (int i=0; i<_configArr.count; i++) {
        NSDictionary *dic = _configArr[i];
        NSArray *arr = dic[@"configInfo"];
        if (i==0) {
            self.modelConfig = arr[0];
        }
        else if (i==1) {
            self.waveConfig = arr[2];
        }
        else if (i==2) {
            self.avgTimeConfig = arr[1];//1-15s  4-60s
        }
        else if (i==3) {
            self.iorConfig = arr[16];
        }
        else if (i==4) {
            self.resolutionRatioConfig = arr[0];
        }
        else if (i==5) {
            self.rangeConfig = arr[0];
        }
        else if (i==6) {
            self.pulseConfig = arr[0];
        }
        else{
            self.attConfig = arr[0];
        }
    }
}


- (void )creatUI{
    UIButton *canshuBtn = [ViewCreate createButtonFrame:CGRectMake(SIZE(20), SIZE(50), SCREEN_WIDTH-SIZE(40), SIZE(50)) title:[LanguageTool DPLocalizedString:@"canshu"] titleColor:RGB51 font:FONT(17) backgroundColor:kThemeColor];
    [self.view addSubview:canshuBtn];
    canshuBtn.layer.masksToBounds = YES;
    canshuBtn.layer.cornerRadius = SIZE(25);
    canshuBtn.tag = 20086;
    [canshuBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *setBtn = [ViewCreate createButtonFrame:CGRectMake(SIZE(20), SIZE(110), SCREEN_WIDTH-SIZE(40), SIZE(50)) title:[LanguageTool DPLocalizedString:@"shezhi"] titleColor:RGB51 font:FONT(17) backgroundColor:kThemeColor];
    [self.view addSubview:setBtn];
    setBtn.layer.masksToBounds = YES;
    setBtn.layer.cornerRadius = SIZE(25);
    setBtn.tag = 20087;
    [setBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *startTestBtn = [ViewCreate createButtonFrame:CGRectMake(SIZE(20), SIZE(190), SCREEN_WIDTH-SIZE(40), SIZE(50)) title:[LanguageTool DPLocalizedString:@"kaishiceshi"] titleColor:RGB51 font:FONT(17) backgroundColor:kThemeColor];
    [self.view addSubview:startTestBtn];
    startTestBtn.layer.masksToBounds = YES;
    startTestBtn.layer.cornerRadius = SIZE(25);
    startTestBtn.tag = 20088;
    [startTestBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *connectBtn = [ViewCreate createButtonFrame:CGRectMake(0,SCREEN_HEIGHT-NavigationHeight-SafeAreaBottomHeight-SIZE(50), SCREEN_WIDTH/2.0, SIZE(50)) title:[LanguageTool DPLocalizedString:@"lianjiejiemian"] titleColor:RGB51 font:FONT(17) backgroundColor:RGB211];
    [self.view addSubview:connectBtn];
    connectBtn.tag = 20087;
    [connectBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    connectBtn.hidden = YES;
    
    
    UIButton *testBtn = [ViewCreate createButtonFrame:CGRectMake(SCREEN_WIDTH/2.0, SCREEN_HEIGHT-NavigationHeight-SafeAreaBottomHeight-SIZE(50), SCREEN_WIDTH/2.0, SIZE(50)) title:[LanguageTool DPLocalizedString:@"ceshijiemian"] titleColor:RGB51 font:FONT(17) backgroundColor:RGB(165, 203, 79)];
    [self.view addSubview:testBtn];
    testBtn.tag = 20088;
    [testBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    testBtn.hidden = YES;
}

- (void )btnAction:(UIButton *)sender{
    if (sender.tag == 20087) {
        //设置参数,将值改成指令形式进行发送
        [self configAllParams];
    }else if(sender.tag == 20088){
        
        [self startTest];
    }
    else{
        ws(weakSelf);
        OTDR_ConfigInfoViewController *vc = [OTDR_ConfigInfoViewController new];
        vc.chooseConfigInfoBlock = ^(NSString * _Nonnull modelConfig, NSString * _Nonnull waveConfig, NSString * _Nonnull avgTimeConfig, NSString * _Nonnull iorConfig, NSString * _Nonnull resolutionRatioConfig, NSString * _Nonnull rangeConfig, NSString * _Nonnull pulseConfig, NSString * _Nonnull attConfig) {
            weakSelf.modelConfig = modelConfig;
            weakSelf.waveConfig = waveConfig;
            weakSelf.avgTimeConfig = avgTimeConfig;
            weakSelf.iorConfig = iorConfig;
            weakSelf.resolutionRatioConfig = resolutionRatioConfig;
            weakSelf.rangeConfig = rangeConfig;
            weakSelf.pulseConfig = pulseConfig;
            weakSelf.attConfig = attConfig;
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//设置所有的参数
- (void )configAllParams{
    self.isTest = NO;
    [ToastView showTitle:[LanguageTool DPLocalizedString:@"canshushezhizhong"]];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{ 
        NSMutableArray *commandArray = [NSMutableArray new];
        //添加波长设置
        [commandArray addObject:[NSString stringWithFormat:@"%@",self.modelConfig]];
        //添加波长设置
        [commandArray addObject:[NSString stringWithFormat:@"WLS %@",self.waveConfig]];
        //添加平均时长设置
        [commandArray addObject:[NSString stringWithFormat:@"ALA 0,%@",self.avgTimeConfig]];
        //添加折射率设置
        [commandArray addObject:[NSString stringWithFormat:@"IOR %@",self.iorConfig]];
        
        if ([self.modelConfig isEqualToString:@"Auto"]) {
            //自动测试
            //添加默认值 距离0,64000、脉宽设置0,160，采样模式1（0，快速/普通分辨率 1，精度/高分辨率）
            [commandArray addObject:[NSString stringWithFormat:@"STP 0,64000,0,160,%@",[self.resolutionRatioConfig isEqualToString:[LanguageTool DPLocalizedString:@"gaofenbianlv"]]?@"1":@"0"]];
            //添加默认att设置
            [commandArray addObject:@"ATT 15"];
        }else{
            //手动测试
            //添加距离、脉宽设置，采样模式1（0，快速/普通分辨率 1，精度/高分辨率）
            [commandArray addObject:[NSString stringWithFormat:@"STP 0,%@,0,%@,%@",self.rangeConfig,self.pulseConfig,[self.resolutionRatioConfig isEqualToString:[LanguageTool DPLocalizedString:@"gaofenbianlv"]]?@"1":@"0"]];
            //添加att设置
            [commandArray addObject:[NSString stringWithFormat:@"ATT %@",self.attConfig]];
        }
        
        
        for (int i=0; i<commandArray.count; i++) {
            NSString *AT_Command = commandArray[i];
            [self.socketServer writeToFCTCPWithData:[AT_Command dataUsingEncoding:NSUTF8StringEncoding]];
            [NSThread sleepForTimeInterval:0.5];
        }
        
        
        dispatch_group_async(group, dispatch_get_main_queue(), ^{
            [ToastView tip:[LanguageTool DPLocalizedString:@"canshushezhiwancheng"]];
        });
    });

    
}

- (void )startTest{
    self.testBackData = [NSMutableData new];
    self.fileNameStr = [NSString new];
    self.totalDataCount =  0;
    
    self.isTest = YES;
    [ToastView showTitle:[LanguageTool DPLocalizedString:@"kaishiceshi"]];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        [self.socketServer writeToFCTCPWithData:[@"LD 1" dataUsingEncoding:NSUTF8StringEncoding]];//开始测量指令
    });
}


//收到socke数据回调函数
-(void)didReadData:(NSData *)data withTag:(long)tag{
    if (self.isTest) {
        [ToastView tip:[LanguageTool DPLocalizedString:@"ceshiwancheng"]];
        // 接收到的消息
        self.fileNameStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"name:%@", self.fileNameStr);
        if ([[self.fileNameStr uppercaseString] containsString:@"FILE"]) {
            NSString *countStr = [self.fileNameStr substringFromIndex:4];
            NSInteger totalCount = [countStr integerValue];
            NSLog(@"总字节长度：%ld",(long)totalCount);
            self.totalDataCount = totalCount;
        }
        
        [self.testBackData appendData:data];
        
       
        NSUInteger length = [self.testBackData length];
        if (length >= 16384*4) {
            NSLog(@"接收完成");
            [self createDir];
            NSString *tiemStamp = [NSString stringWithFormat:@"%@.EI",[LLUtils dateStrWithDate:[NSDate date] dateFormat:@"yyyyMMddHHmmss"]];
            [self createFileWithFileName:tiemStamp data:self.testBackData];
        
            [self dealTestBackDataWithTotalData:self.testBackData];
        }
    }
    else{
        // 接收到的消息
        NSString *messageStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", messageStr);
    }
}

//处理测试完成返回的数据
- (void )dealTestBackDataWithTotalData:(NSData *)totalData{
    OTDR_LF_DrawViewController *vc = [OTDR_LF_DrawViewController new];
    vc.drawData = totalData;
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self  presentViewController:vc animated:NO completion:nil];
}


//创建文件夹

- (void)createDir{
    
    NSString*documentsPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager      = [NSFileManager defaultManager];
    NSString      *testDirectory    = [documentsPath stringByAppendingPathComponent:@"EIFile"];
    
    BOOL isExists = [fileManager fileExistsAtPath:testDirectory];
    if (isExists) {
        return;
    }
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        NSLog(@"文件夹创建成功");
    }else{
        NSLog(@"文件夹创建失败");
    }
}

//创建文件
- (void)createFileWithFileName:(NSString *)fileName data:(NSData *)data{
    NSString      *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString      *testDirectory = [documentsPath stringByAppendingPathComponent:@"EIFile"];
    NSFileManager *fileManager   = [NSFileManager defaultManager];
    NSString      *fileUrl      = [testDirectory stringByAppendingPathComponent:fileName];
    
    BOOL res = [fileManager createFileAtPath:fileUrl contents:nil attributes:nil];
    if (res) {
        NSLog(@"文件创建成功: %@" ,fileUrl);
    }else{
        NSLog(@"文件创建失败");
    }
    
    BOOL writeOk = [data writeToFile:fileUrl atomically:YES];
    if (writeOk) {
        NSLog(@"文件写入成功");
    }else{
        NSLog(@"文件写入失败");
    }
    
}

@end
